//
//  TRUserRegisterViewController.m
//  WeiMiLan
//
//  Created by anan on 14/12/28.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRUserRegisterViewController.h"

@interface TRUserRegisterViewController ()

@end

@implementation TRUserRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initNavigation];
    
    self.textFieldPhoneNum.delegate = self;
    self.textFieldCode.delegate = self;
    self.textFieldNickname.delegate = self;
    self.textFieldPassword1.delegate = self;
    self.textFieldPassword2.delegate = self;
    
    NSAttributedString *str = [[NSAttributedString alloc] initWithString:self.textFieldCode.placeholder attributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
    self.textFieldCode.attributedPlaceholder = str;
    
    str = [[NSAttributedString alloc] initWithString:self.textFieldNickname.placeholder attributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
    self.textFieldNickname.attributedPlaceholder = str;
    
    str = [[NSAttributedString alloc] initWithString:self.textFieldPassword1.placeholder attributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
    self.textFieldPassword1.attributedPlaceholder = str;
    
    str = [[NSAttributedString alloc] initWithString:self.textFieldPassword2.placeholder attributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
    self.textFieldPassword2.attributedPlaceholder = str;
    
    str = [[NSAttributedString alloc] initWithString:self.textFieldPhoneNum.placeholder attributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
    self.textFieldPhoneNum.attributedPlaceholder = str;
    
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
}

- (IBAction)buttonSendCodeAction:(UIButton *)sender
{
    if ([self.textFieldPhoneNum.text isEqualToString:@""]) {
        [SVProgressHUD showImage:nil status:@"请输入手机号"];
        return;
    }
    if (![QLUserManager isMobileNumber:self.textFieldPhoneNum.text]) {
        [SVProgressHUD showImage:nil status:@"手机号格式有误"];
        return;
    }
    __weak typeof(self) weakSelf = self;
    [QLMaskUtil showMaskLoadingWithView:self.view1];
    
    [self sendMsg];
    
}

- (IBAction)buttonSubmitCodeAction:(UIButton *)sender
{
    [QLMaskUtil showMaskLoadingWithView:self.view];
    [SMSSDK  commitVerificationCode:self.textFieldCode.text
     //传获取到的区号
                        phoneNumber:self.textFieldPhoneNum.text
                               zone:@"86"
                             result:^(NSError *error)
     {
         [QLMaskUtil hideLoadingMaskWithView:self.view];
         if (!error)
         {
             self.view2.hidden = YES;
             self.view3.hidden = NO;
             NSLog(@"验证成功");
             
         }
         else
         {
             [SVProgressHUD showImage:nil status:@"验证码错误"];
             NSLog(@"验证失败");
             return;
         }
         
     }];
}

- (void)sendMsg
{
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS
     //这个参数可以选择是通过发送验证码还是语言来获取验证码
                            phoneNumber:self.textFieldPhoneNum.text
                                   zone:@"86"
                       customIdentifier:nil //自定义短信模板标识
                                 result:^(NSError *error)
     {
         [QLMaskUtil hideLoadingMaskWithView:self.view1];
         if (!error)
         {
             [SVProgressHUD showImage:nil status:@"验证码已发送"];
             self.view1.hidden = YES;
             self.view2.hidden = NO;
             self.labelPhoneNum.text = self.textFieldPhoneNum.text;
             
         }
         else
         {
             [SVProgressHUD showImage:nil status:@"验证码发送失败"];
         }
         
     }];
}

- (IBAction)buttonRegisterAction:(UIButton *)sender {
    if ([self.textFieldNickname.text isEqualToString:@""]) {
        [SVProgressHUD showImage:nil status:@"请输入昵称"];
        return;
    }
    
    if ([self.textFieldPhoneNum.text isEqualToString:@""]) {
        [SVProgressHUD showImage:nil status:@"请输入手机号"];
        return;
    }
    
    if (![QLUserManager isMobileNumber:self.textFieldPhoneNum.text]) {
        [SVProgressHUD showImage:nil status:@"手机号格式有误"];
        return;
    }
    if ([self.textFieldPassword1.text isEqualToString:@""]) {
        [SVProgressHUD showImage:nil status:@"请输入密码"];
        return;
    }
    if ([self.textFieldPassword2.text isEqualToString:@""]) {
        [SVProgressHUD showImage:nil status:@"请重新输入密码"];
        return;
    }
    
    if (![self.textFieldPassword1.text isEqualToString:self.textFieldPassword2.text]) {
        [SVProgressHUD showImage:nil status:@"密码输入不一致"];
        return;
    }
    
    if ([self.textFieldCode.text isEqualToString:@""]) {
        [SVProgressHUD showImage:nil status:@"请输入验证码"];
        return;
    }
//    
//    if (![self.textFieldCode.text isEqualToString:self.verifCode]) {
//        [SVProgressHUD showImage:nil status:@"验证码错误"];
//        return;
//    }
    
    [SVProgressHUD showWithStatus:@"注册中…"];
    
    double delayInSeconds = 5;\
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);\
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        if ([SVProgressHUD isVisible]) {
            [SVProgressHUD dismiss];
        }
    });
    NSDictionary *params=@{
                           REGISTER_PASS_WORD: self.textFieldPassword1.text,
                           @"REFERRER_ID":@"",
                           REGISTER_NAME:self.textFieldNickname.text,
                           @"MAC":[QLPublic macaddress],
                           REGISTER_REGION:@"深圳",
                           REGISTER_PHONE:self.textFieldPhoneNum.text,
                           @"DEVICE_TYPE":OS_TYPE_IOS
                           };
    NSLog(@"注册的信息：%@",params);
    
    [ApplicationDelegate.webAPI getWebAPIWithParams:params andMethodNode:NODE_REGISTER completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
        
        if (state==1) {
            NSLog(@"注册成功");
            NSString * message = responseObject[@"MESSAGE_INFO"][@"MESSAGE"];
            
            if ([responseObject[@"MESSAGE_INFO"][@"CODE"] isEqualToString:@"0000"]) {
                
                if (message.length>2) {
                    //自动登陆一次
                    [ApplicationDelegate.webAPI logInWithUserName:self.textFieldPhoneNum.text andPassword:self.textFieldPassword1.text completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
                        if (state==1&&responseObject) {
                            NSString *msg=[NSString stringWithFormat:@"%@",responseObject[@"MESSAGE_INFO"][@"CODE"]];
                            if ([msg isEqualToString:@"0000"]) {
                                [SVProgressHUD showSuccessWithStatus:@"注册成功"];
                                
                                //去用户id
                                NSString *idString=responseObject[@"LOGIN_USER_RSP"][@"UPLOAD_URL"];
                                NSArray *idArr=[idString componentsSeparatedByString:@"?userId="];
                                ApplicationDelegate.currentUserId=[idArr lastObject];
                                ApplicationDelegate.uploadUrl = [NSURL URLWithString:idString];
                                [NSStandardUserDefaults setObject:self.textFieldPhoneNum.text forKey:@"USER_NAME"];
                                [NSStandardUserDefaults setObject:self.textFieldPassword1.text forKey:@"USER_PASSWORD"];
                                [NSStandardUserDefaults setObject:[idArr lastObject] forKey:@"USER_ID"];
                                [NSStandardUserDefaults setObject:idString forKey:@"USER_URL"];
                                [NSStandardUserDefaults synchronize];
                                NSString *uid = [NSString stringWithFormat:@"%@",[idArr lastObject]];
                                [[QLUserManager shareInstance] saveUserInfo:responseObject[@"LOGIN_USER_RSP"]];
                                [[QLUserManager shareInstance] detailWithUserId:(int)[uid integerValue] callback:nil];
                                self.textFieldNickname.text = @"";
                                self.textFieldPhoneNum.text = @"";
                                self.textFieldPassword1.text = @"";
                                self.textFieldPassword2.text = @"";
                                
                                //完成退出
                                UIViewController * vc;
                                vc = [[QLPlayerManager getStoryboard] instantiateViewControllerWithIdentifier:@"TRTabBarViewController"];
                                [self.navigationController pushViewController:vc animated:YES];
                                [self presentViewController:vc animated:YES completion:nil];
                                
                            }else
                            {
                                if ([msg isEqualToString:@"9998"]) {
                                    [SVProgressHUD showSuccessWithStatus:@"用户名或密码错误"];
                                }
                            }
                        }
                    }];
                }
            }else{
                if (message.length>2) {
                    [SVProgressHUD showErrorWithStatus:message];
                }
            }
        }
        else{
            [SVProgressHUD showSuccessWithStatus:@"注册失败"];
        }
    }];
    
    
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    self.weChatNavigationBar.titleLabel.text=@"";
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(exit) forControlEvents:UIControlEventTouchUpInside];
    self.weChatNavigationBar.rightButton.hidden = YES;
}

- (void)exit
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)viewTapped:(UITapGestureRecognizer*)tapGr{
    [self.textFieldCode resignFirstResponder];
    [self.textFieldNickname resignFirstResponder];
    [self.textFieldPassword1 resignFirstResponder];
    [self.textFieldPassword2 resignFirstResponder];
    [self.textFieldPhoneNum resignFirstResponder];
    

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -- UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField==self.textFieldPhoneNum) {
        [self.textFieldPhoneNum resignFirstResponder];
    }else if(textField==self.textFieldCode){
        [self.textFieldCode resignFirstResponder];
    }else if(textField==self.textFieldNickname){
        [self.textFieldPassword1 becomeFirstResponder];
    }else if(textField==self.textFieldPassword1){
        [self.textFieldPassword2 becomeFirstResponder];
    }else{
        [textField resignFirstResponder];
    }
    return YES;
}

@end
